package com.frinder.seata.account.service;

import com.frinder.seata.data.base.Result;
import com.frinder.seata.data.domain.model.Account;
import com.frinder.seata.data.domain.service.IAccountService;
import com.frinder.seata.data.utils.ThreadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Optional;

@Slf4j
@Service
public class BizAccountService {

    @Resource
    private IAccountService accountService;

    @Resource
    private CallOrderService callOrderService;

    /**
     * 扣减金额 & 完成订单
     *
     * @param timeout
     * @param userId
     * @param money
     * @param orderId
     * @param circle
     */
    public void decrease(boolean timeout, long userId, BigDecimal money, long orderId, boolean circle) {
        log.info(">> 开始扣减账户[{}]，扣减金额[{}]，扣减订单[{}]", userId, money, orderId);
        Optional.ofNullable(accountService.findBy("userId", userId))
                .ifPresent(o -> {
                    long longMoney = money.longValue();
                    Account account = Account.builder()
                            .id(o.getId())
                            .residue(o.getResidue() - longMoney)
                            .used(o.getUsed() + longMoney)
                            .build();
                    accountService.update(account);
                    log.info("<< 已扣减账户[{}]，扣减金额[{}]，扣减订单[{}]", userId, money, orderId);
                });
        // 模拟超时
        if (timeout) {
            ThreadUtils.sleep(30_000);
        }
        if (circle) {
            log.info(">> 请求修改订单状态");
            Result result = callOrderService.completed(orderId);
            log.info(">> 修改订单状态结果[{}]", result);
        }
    }

}
